﻿#region Using

using System;
using System.Linq;
using System.Net;
using WSMon.Core.Configuration;
using WSMon.Core.Interfaces;

#endregion

namespace WSMon.Core.Checkers.Web
{
    public class DnsChecker : Checker, IChecker
    {
        private readonly DnsConfiguration _dnsConfiguration;

        private string _logs = string.Empty;

        public DnsChecker(DnsConfiguration dnsConfiguration)
        {
            if (dnsConfiguration == null)
                throw new ArgumentNullException("dnsConfiguration");

            _dnsConfiguration = dnsConfiguration;
        }

        #region IChecker Members

        public bool CheckOut()
        {
            try
            {
                var hostAddresses = Dns.GetHostAddresses(_dnsConfiguration.Host);
                var aryHostAddress = new string[hostAddresses.Length];

                for (int i = 0; i < hostAddresses.Length; i++)
                {
                    aryHostAddress[i] = hostAddresses[i].ToString();
                }

                bool hasError = false;
                foreach (var ipAddress in _dnsConfiguration.IpAddresses)
                {
                    if (!aryHostAddress.Contains(ipAddress))
                    {
                        _logs += string.Format("{0} was not found. ", ipAddress);
                        hasError = true;
                    }
                }

                return !hasError;
            }
            catch (Exception ex)
            {
                _logs = ex.Message;
                return false;
            }
        }

        public string GetLogs()
        {
            return _logs;
        }

        #endregion
    }
}